package com.ellricky.baselib.http;


import com.ellricky.baselib.BuildConfig;
import com.orhanobut.logger.Logger;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * Created by zhy on 16/3/1.
 */
public class LoggerInterceptor implements Interceptor {
    public static final String TAG = "OkHttpUtils";
    private boolean showResponse;

    public LoggerInterceptor( boolean showResponse) {
        this.showResponse = showResponse;
    }



    @SuppressWarnings("NullableProblems")
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();

        Response response = chain.proceed(request);
        boolean isRelease = "release".equals(BuildConfig.BUILD_TYPE);
        if (isRelease){
            return response;
        }
        logForRequest(request);
        return logForResponse(response);
    }

    private Response logForResponse(Response response) {
      if (showResponse){
          Response.Builder builder = response.newBuilder();
          Response clone = builder.build();
          ResponseBody body = clone.body();
          Logger.t(TAG).e("响应体：%s",
                  "url : " + clone.request().url() +"；\n" +
                          "body : " + body + "；\n"
          );
          return response.newBuilder().body(body).build();
      }


        return response;
    }

    private void logForRequest(Request request) {
        Logger.t(TAG).e("请求体：%s",
                request.url() +"\n" +
                        request.headers() + "+\n" +
                        request.body()
        );
    }
}
